package com.bw.common.interceptor;

import com.bw.common.IpUtils;
import com.bw.common.ResponseResult;
import com.bw.common.anno.AnRule;
import com.bw.common.auth.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate<String,Object> redisTemplate ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
       //获取cookie中的token值
            Cookie[] cookies = request.getCookies();
            String token="";
            for (Cookie cookie: cookies) {
                if(cookie.getName().equals("token")){
                    token=cookie.getValue();
                }
        }
        //根据token获取redis中的用户信息
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        if(userInfo==null){
            return false;
        }else{
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(1800);//超时时间
            cookie.setPath("/");
            response.addCookie(cookie);

        }


        HandlerMethod handlerMethod= (HandlerMethod) handler;//获取当前请求接口的注解
        AnRule anRule = handlerMethod.getMethodAnnotation(AnRule.class);
        if(anRule!=null){
            int num=anRule.num();
            int time=anRule.time();
            //获取客户端的IP地址（根据request获取）
            String ip = IpUtils.getIpAddress(request);
            //记录开始时间，和访问次数 以ip:time 作为key 记录时间 以ip:count作为key统计次数
            redisTemplate.opsForValue().setIfAbsent(ip+":time",System.currentTimeMillis());

            Long nowTime=System.currentTimeMillis();//当前访问的时间
            Long firstTime= (Long) redisTemplate.opsForValue().get(ip+":time");//第一次访问时间

            if((nowTime-firstTime)<=time){//一分钟之内计数
                Long count=redisTemplate.opsForValue().increment(ip+":count");
                if(count>num){
                    response.getOutputStream().write("响应次数频繁".getBytes());
                }
            }else {
                //删除时间和计数
                redisTemplate.delete(ip+":time");
                redisTemplate.delete(ip+":count");
            }
        }



        return true;
    }
}
